from flask import Response, Blueprint
import cv2
import numpy as np
from cap import VideoCapture

video_bp = Blueprint('video', __name__, url_prefix='/api')

@video_bp.route('/video_feed')
def video_feed():
    def generate():
        cap = VideoCapture()

        while True:
            frame = cap.read()
            if frame is None:
                # print("错误：读取到空帧")
                yield b'--frame\r\nContent-Type: text/plain\r\n\r\nError: No frame available\r\n'
                break
            if not isinstance(frame, np.ndarray):
                # print(f"错误：frame 类型不正确，实际类型: {type(frame)}")
                yield b'--frame\r\nContent-Type: text/plain\r\n\r\nError: Invalid frame type\r\n'
                break
            # 检查帧是否全黑
            if np.mean(frame) < 5:  # 如果帧的像素均值很低，可能是黑帧
                print(f"警告：帧可能是黑的，像素均值: {np.mean(frame)}")
            #print(f"帧形状: {frame.shape}, 像素均值: {np.mean(frame)}")
            ret, buffer = cv2.imencode('.jpg', frame)
            if not ret:
                print("错误：帧编码失败")
                continue
            frame_bytes = buffer.tobytes()
            # print(f"编码后数据大小: {len(frame_bytes)} 字节")
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
        cap.release()
    return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')